package com.colorfruit.admin.business.service.impl;
import java.math.BigDecimal;

import com.colorfruit.admin.business.dao.*;
import com.colorfruit.admin.business.service.ShopCartService;
import com.colorfruit.admin.pojo.entity.*;
import com.colorfruit.admin.pojo.enums.ErrorCodeEnum;
import com.colorfruit.admin.pojo.enums.StatusEnum;
import com.colorfruit.admin.pojo.vo.payorder.PayOrderItemVo;
import com.colorfruit.admin.pojo.vo.preonshelf.PreOnShelfVo;
import com.colorfruit.admin.pojo.vo.shopcard.ShopCartVo;
import com.colorfruit.framework.common.util.BusinessUtil;
import com.colorfruit.framework.common.util.CommonUtil;
import com.colorfruit.framework.common.util.DataValidateUtil;
import com.colorfruit.framework.model.admin.CommonDate;
import com.colorfruit.framework.model.pojo.BaseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ShopCartServiceImpl implements ShopCartService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper; //购物车

    @Autowired
    PreShelfOrderMapper preShelfOrderMapper; //预上架订单

    @Autowired
    PayBusinessOrderMapper payBusinessOrderMapper;//支付业务订单

    @Autowired
    PayBusinessOrderItemMapper payBusinessOrderItemMapper;

    @Autowired
    FoundationProductMapper foundationProductMapper;//产品mapper

    @Autowired
    GlobalProcessionControlMapper globalProcessionControlMapper;

    @Override
    public BaseResult addToShopCart(String userId, Long preShelfOrderId, Integer buyNum) {
        try {
            log.info("[service] [IN] addToShopCart param : userId = {}, preShelfOrderId = {}, buyNum = {}", userId, preShelfOrderId, buyNum);
            GlobalProcessionControl recentProcession = globalProcessionControlMapper.getRecentProcession();
            if (!DataValidateUtil.verifyString(userId)){
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "用户ID不能为空");
            }
            if (preShelfOrderId == null || preShelfOrderId == 0){
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "预上架订单ID不能为空");
            }
            PreShelfOrder preShelfOrder = preShelfOrderMapper.selectByPrimaryKey(preShelfOrderId);
            if (preShelfOrder == null){
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "没有preShelfOrderId = "+ preShelfOrderId + "的预上架订单");
            }
            CommonDate commonDate = BusinessUtil.getCommonDate();
            ShoppingCart shoppingCartDB = shoppingCartMapper.getDataByPreShelfId(userId, preShelfOrderId, commonDate.getTheDayBegin(), commonDate.getTheDayEnd());
            if (shoppingCartDB == null){
                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.setPreShelfOrderId(preShelfOrderId);
                shoppingCart.setUserId(userId);
                shoppingCart.setProductId(preShelfOrder.getProductId());
                shoppingCart.setBuyNum(buyNum);
                shoppingCart.setRecordStatus(StatusEnum.EFFECTIVE_STATUS.getStatusCode());
                shoppingCart.setGlobalControlId(recentProcession.getId());
                shoppingCartMapper.insert(shoppingCart);
            }else {
                shoppingCartDB.setBuyNum( buyNum + shoppingCartDB.getBuyNum());
                shoppingCartDB.setUpdateTime(new Date());
                shoppingCartMapper.updateByPrimaryKeySelective(shoppingCartDB);
            }
            log.info("[service] [OUT] addToShopCart success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<ShopCartVo> selectShopCartList(String userId, String productName, int page, int size) {
        try {
            log.info("[service] [IN] selectShopCartList param : userId = {}, productName = {}, page = {}, size = {}", userId, productName, page, size);
            GlobalProcessionControl recentProcession = globalProcessionControlMapper.getRecentProcession();
            List<ShopCartVo> shoppingCarts = shoppingCartMapper.selectShoppingCartList(
                    userId,
                    productName,
                    size,
                    recentProcession.getId());
            log.info("[service] [OUT] selectShopCartList success ");
            return shoppingCarts;
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public PageInfo<ShopCartVo> selectHistoryShopCartList(String userId, String productName, int page, int size) {
        log.info("[service] [IN] selectHistoryShopCartList param : userId = {}, productName = {}, page = {}, size = {}", userId, productName, page, size);
        PageHelper.startPage(page, size);
        List<PayBusinessOrderItem> payOrderItemVos = payBusinessOrderItemMapper.selectHistoryShopCartList(userId, productName);
        PageInfo<PayBusinessOrderItem> payOrderItemVoPageInfo = new PageInfo<>(payOrderItemVos);
        List<ShopCartVo> shopCartVos = new ArrayList<>();
        for (PayBusinessOrderItem payOrderItemVo : payOrderItemVos){
            ShopCartVo shopCartVo = new ShopCartVo();
            FoundationProduct foundationProduct = foundationProductMapper.selectByPrimaryKey(payOrderItemVo.getProductId());
            CommonDate commonDate = BusinessUtil.getCommonDate();
            List<PreShelfOrder> preShelfOrderList = preShelfOrderMapper.selectTodayProduct(payOrderItemVo.getProductId(), commonDate.getTheDayBegin(), commonDate.getTheDayEnd());

            shopCartVo.setProductId(payOrderItemVo.getProductId());
            shopCartVo.setUserId(payOrderItemVo.getUserId());
            shopCartVo.setPreShelfOrderId(0L);
            shopCartVo.setProductName(foundationProduct.getProductName());
            shopCartVo.setProductSpecifications(foundationProduct.getProductSpecifications());
            shopCartVo.setProductPlace(foundationProduct.getProductPlace());
            shopCartVo.setProductVariety(foundationProduct.getProductVariety());
            shopCartVo.setProductType(foundationProduct.getProductType());
            shopCartVo.setMarketMonth(foundationProduct.getMarketMonth());
            shopCartVo.setPackageType(foundationProduct.getPackageType());
            shopCartVo.setPackageVolume(foundationProduct.getPackageVolume());
            shopCartVo.setProductGrossWeight(foundationProduct.getProductGrossWeight());
            shopCartVo.setProductNetWeight(foundationProduct.getProductNetWeight());
            shopCartVo.setProductLevel(foundationProduct.getProductLevel());
            shopCartVo.setProductSmallPic(foundationProduct.getProductSmallPic());
            shopCartVo.setProductBigPic(foundationProduct.getProductBigPic());
            shopCartVo.setDescriptionPics(foundationProduct.getDescriptionPics());
//            shopCartVo.setBrand("");
            if (preShelfOrderList.size() > 0){
                PreShelfOrder preShelfOrder = preShelfOrderList.get(0);
                shopCartVo.setBuyNum(0);
                shopCartVo.setGoodLabel(preShelfOrder.getGoodLabel());
                shopCartVo.setSaleReferMaxPrice(preShelfOrder.getSaleReferMaxPrice());
                shopCartVo.setSaleReferMinPrice(preShelfOrder.getSaleReferMinPrice());
                shopCartVo.setSaleMaxPrice(preShelfOrder.getSaleMaxPrice());
                shopCartVo.setSaleMinPrice(preShelfOrder.getSaleMinPrice());
                shopCartVo.setLimitSaleNum(preShelfOrder.getLimitSaleNum());
                shopCartVo.setSingleCusLimitNum(preShelfOrder.getSingleCusLimitNum());
                shopCartVo.setShareTitle(preShelfOrder.getShareTitle());
                shopCartVo.setSharePicUrl(preShelfOrder.getSharePicUrl());
                shopCartVo.setPreShelfOrderId(preShelfOrder.getId());
            }
            shopCartVos.add(shopCartVo);
        }
        PageInfo<ShopCartVo> shopCartVoPageInfo = new PageInfo<>(shopCartVos);
        shopCartVoPageInfo.setSize(payOrderItemVoPageInfo.getSize());
        log.info("[service] [OUT] selectHistoryShopCartList success ");
        return shopCartVoPageInfo;
    }

    @Override
    public Integer deleteProduct(String userId, String shoppingCartIds) {
        log.info("[service] [IN] deleteProduct param : userId = {}, shoppingCartIds = {}", userId, shoppingCartIds);
        String[] idArray = shoppingCartIds.split(",");
        for (String id : idArray){
            shoppingCartMapper.deleteProduct(userId, Long.parseLong(id));
        }
        log.info("[service] [OUT] deleteProduct success ");
        return 1;
    }
}
